import { defineStore } from 'pinia'
import { ElMessageBox, ElMessage } from 'element-plus'
import chatApi from '@/apis/chat'
import { useAuthStore } from './auth'

const authStore = useAuthStore()
export const useChatStore = defineStore('chat', {
  state: () => ({
    data: [],
    active: null,
    initialized: false,
    subscribed: false,
  }),
  actions: {
    async init() {
      if (!this.initialized) {
        await this.getData()
        this.initialized = true
      }
      //订阅auth状态
      if (!this.subscribed) {
        authStore.$subscribe((mutation, state) => {
          if (mutation.storeId === 'auth' && !state.isAuthenticated) {
            this.clearStore()
          }
        })
        this.subscribed = true
      }
    },
    async getData() {
      this.data = (await chatApi.unlimited.list()).data
    },
    async getSession(id, setActive = true) {
      const session = (await chatApi.unlimited.read(id)).data
      if (setActive) {
        this.active = session
      }
      return session
    },
    setActive(session) {
      this.active = session
    },
    clearStore() {
      this.data = []
      this.active = null
      this.initialized = false
    },
    displayStyle(style = '', defaultValue = 'list') {
      if (style) {
        localStorage.setItem('displayStyle', style)
      } else {
        return localStorage.getItem('displayStyle') || defaultValue
      }
    },
    create() {
      return new Promise((resolve, reject) => {
        let step = 1
        ElMessageBox.prompt('', '新建对话', {
          inputValue: '新的对话',
          inputPlaceholder: '请输入名称',
          inputPattern: /^.{1,60}$/,
          inputErrorMessage: '名称不能为空且不能超过60个字符',
        })
          .then(({ value }) => {
            step++
            return chatApi.unlimited.create({ name: value })
          })
          .then(async ({ data }) => {
            step++
            this.setActive(data)
            ElMessage.success('创建成功')
            this.getData()
            resolve(data)
          })
          .catch((error) => {
            console.log('error', step, error)
            reject(error)
          })
      })
    },
    rename(id) {
      return new Promise((resolve, reject) => {
        const session = this.data.find((s) => s.id === id)
        if (!session) {
          ElMessage.warning('会话不存在')
          reject()
        }
        ElMessageBox.prompt('', '修改名称', {
          inputValue: session.name,
          inputPlaceholder: '请输入名称',
          inputPattern: /^.{1,60}$/,
          inputErrorMessage: '名称不能为空且不能超过60个字符',
        })
          .then(({ value }) => chatApi.unlimited.update(id, { name: value }))
          .then(({ data }) => {
            if (this.active?.id === session.id) {
              this.active.name = data.name
            }
            //修改this.data里的session name
            this.data.forEach((item) => {
              if (item.id === session.id) {
                item.name = data.name
              }
            })
            ElMessage.success('修改成功')
            resolve()
          })
          .catch((err) => {
            console.log(err)
            reject(err)
          })
      })
    },
    remove(id) {
      return new Promise((resolve, reject) => {
        const session = this.data.find((s) => s.id === id)
        if (!session) {
          ElMessage.warning('会话不存在')
          reject()
        }
        ElMessageBox.confirm('确定要删除会话吗？', '提示', { type: 'warning' })
          .then(() => chatApi.unlimited.delete(id))
          .then(() => {
            this.data.splice(this.data.indexOf(session), 1)
            if (this.active?.id === session.id) {
              this.setActive(null)
            }
            ElMessage.success('删除成功')
            resolve()
          })
          .catch((err) => {
            console.log(err)
            reject(err)
          })
      })
    },
  },
})
